from django.shortcuts import render
from django.http import HttpResponse
import json
from django.views.decorators.csrf import csrf_exempt
from activity.models import ActivityEnroll, Activity

from activity.forms import ActivityEnrollForm

# Create your views here.
# 加个装饰器绕过csrf验证


@csrf_exempt
def activity_enroll_view(request):
    if request.method == 'POST':
        activity_id = request.POST['activity_id']
        if activity_id:
            form = ActivityEnrollForm(request.POST)
            # 因为我们要把活动报名者的信息传到对应的活动中，因此我们先获取到活动实体，然后赋值给form，再保存
            activity = Activity.objects.get(id=activity_id)

            if form.is_valid():
                enroll = form.save(commit=False)
                enroll.activity = activity
                enroll.save()
                enroll_name = form.cleaned_data['enroll_name']
                enroll_gender = form.cleaned_data['enroll_gender']

                response_dict = {
                    'status': 'success',
                    'name': enroll_name,
                    'gender': enroll_gender
                }
                return HttpResponse(json.dumps(response_dict), content_type='application/json')
            else:
                return HttpResponse('form not valid.')
        else:
            return HttpResponse('必须指定活动id.')
    else:
        return HttpResponse('<p>Bad request!!!!!!!!Only support post method. </p>')


